<?php
use \think\facade\Db;
use Firebase\JWT\JWT;
use api\web\model\UserModel;
use \api\web\model\MoneyModel;
//公共函数
//统一成功返回
function success($msg = '',$data=null){
    return json([
        'code'=>1,
        'msg'=>$msg,
        'data'=>$data
    ]);
}
//统一失败返回
function error($msg = '',$data=null){
    return json([
        'code'=>0,
        'msg'=>$msg,
        'data'=>$data
    ]);
}
//生成随机字符串
function createRandStr($length = 8){
   $str="0123456789ABCDEFGHIGKLMNOPQISJUVWSYZ" ;
   $randSte = '';
   for($i=0;$i<$length;$i++){
       $randSte.=$str[mt_rand(0,35)];
   }

   return $randSte;
}
function signToken($userId, $mobile)
{
    $data = [
        // 签发人
        'iss' => request()->domain(),
        // 签发时间
        'iat' => time(),
        // 自定义数据
        'data' => [
            'user_id' => $userId,
            'mobile' => $mobile,
        ]
    ];
    $key = config('app.jwt_key');
    $token = JWT::encode($data, $key, 'HS256');
    return $token;
}




function checkSmsCode($mobile, $code)
{
    $log =Db::name('sms_code_log')->where('mobile', $mobile)->find();
    if (!$log) {
        return false;
    }
    if ($log['code'] != $code) {
        return false;
    }
    if (time() - $log['send_time'] > 300) { // 验证码有效期5分钟
        Db::name('sms_code_log')->where('mobile', $mobile)->delete();
        return false;
    }
    Db::name('sms_code_log')->where('mobile', $mobile)->delete();
    return true;
}

//查询用户流水
function Getmoney($user_id)
{
    // 查询用户的流水记录
    $logs = MoneyModel::
    where('user_id', $user_id)
        ->order('create_time', 'desc')
        ->select();

    if (!$logs) {
        throw new Exception('没有找到流水记录');
    }

    return $logs;
}

//添加流水记录
function add_money_log($user_id, $money, $reason, $type = 1)
{
    // 获取用户信息
    $user = UserModel::where('id', $user_id)->find();
    if (!$user) {
        throw new Exception('用户不存在');
    }

    // 计算新的余额
//    $newBalance = $user['wallet'] + $money;
    if ($type == 1){
        $newBalance = $user['wallet'] + $money;
    } elseif ($type == 0){
        $newBalance = $user['wallet'] - $money;
    } else {
        throw new Exception('无效的类型');
    }

    // 更新用户余额
    UserModel::where('id', $user_id)->update(['wallet' => $newBalance]);

    // 记录流水
    MoneyModel::insert([
        'user_id' => $user_id,
        'money' => $money,
        'reason' => $reason,
        'before' => $user['wallet'],
        'after' => $newBalance,
        'type' => $type, // 类型：1-存储
        'create_time' => date('Y-m-d H:i:s')
    ]);

    return $newBalance;
}


//
function record($user_id)
{
    // 查询用户的流水记录
    $logs = Db::name('money')
        ->where('user_id', $user_id)
        ->order('create_time', 'desc')
        ->select();

    if (!$logs) {
        throw new Exception('没有找到流水记录');
    }

    return $logs;
}

